package database

import (
	"hg/models"

	"github.com/sirupsen/logrus"
)

func InsertOneUser(user *models.Userinfo) error {
	_, err := engine.InsertOne(user)
	return err
}

func GetUserinfoByUsername(username string) (*models.Userinfo, error) {
	user := &models.Userinfo{
		Username: username,
	}
	exist, err := engine.Where("username = ?", username).Get(user)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return user, nil
}

func GetUserinfoByUserId(userId int) (*models.Userinfo, error) {
	user := &models.Userinfo{
		Id: userId,
	}
	exist, err := engine.Where("id = ?", userId).Get(user)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return user, nil
}


func GetAllUserinfo() ([]*models.Userinfo, error) {
	var users []*models.Userinfo
	err := engine.Find(&users)
	if err != nil {
		logrus.Errorln(err)
		return nil, err
	}
	return users, nil
}

func UpdateUserinfo(user *models.Userinfo, cols ...string) error {
	_, err := engine.Where("username = ?", user.Username).Cols(cols...).Update(user)
	return err
}

func GetUserinfoByVideoId(videoId int) (*models.Userinfo, error) {
	video := &models.Videos{
		Id: videoId,
	}
	exist, err := engine.Where("id = ?", videoId).Get(video)
	if err != nil {
		logrus.Error("serach video from db failed", err)
		return nil, err
	}
	if !exist {
		logrus.Error("video not exist")
		return nil, err
	}
	user,_:=GetUserinfoByUserId(video.UserInfo)
	return user,nil
}
